const fs= require('fs');
const path= require('path');
const url= require('url');
 
var events =require('events');
var EventEmitter =new events.EventEmitter(); 
function getMime(extname,EventEmitter){   
     
    fs.readFile('./mime.json',(err,data)=>{
        if(err){
            console.log('文件不存在');
            return;
        }
        let Mime = JSON.parse(data.toString());
        EventEmitter.emit('emit_mime',Mime[extname]||'text/html')
        // callback(Mime[extname]||'text/html')
        // return Mime[extname] ;
    }) 
}
exports.statics=function(req,res,staticPath){
    
    //使用path模块中的extname方法获取文件后缀名
    

    let pathname=url.parse(req.url).pathname ;
    if(pathname=='/'){
        pathname='index.html'
        
    }
    var extname=path.extname(pathname) 
    if (pathname!=='./favicon.ico') {
        fs.readFile(staticPath+'/'+pathname,(err,data)=>{

            if(err){
                fs.readFile(staticPath+'/404.html',(err,data_404)=>{                    
                    res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});
                    res.write(data_404)
                    res.end();
                });
                return;
            }else{
                getMime(extname,EventEmitter)
                EventEmitter.on('emit_mime',(mime)=>{
                    res.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});
                    // res.write()
                    res.end(data);
                })
            }
            
        })
    }
  


}